var contextPath = function() {
return  "/" + location.pathname.split("/")[1];
}

var _menus = {};

//初始化左侧
function InitLeftMenu() {
var obj = $.ajax({url:"./auth/getLoginUserFunctionTree",async:false});
var res = eval("(" + obj.responseText + ")");
var functionTree =  res.function_tree.root;
_menus = createMenuTree(functionTree);

$("#nav").accordion({animate:false});

$.each(_menus.menus, function(i, n) {
    var menulist ='';
    menulist +='<ul class="easyui-tree">';
    $.each(n.menus, function(j, o) {
        menulist += '<li>';
        menulist += '<span>' + o.menuname + '</span>';
        menulist += '<ul>';
        $.each(o.menus, function(k, l) {
            menulist += '<li><div><a ref="'+l.menuid+'" href="#" rel="' + l.url + '" style="text-decoration:none;"><span class="icon '+l.icon+'" >&nbsp;</span><span class="nav">' + l.menuname + '</span></a></div></li> ';
        });
        menulist += '</ul>';
        menulist += '</li>';
    });
    menulist += '</ul>';

    $('#nav').accordion('add', {
        title: n.menuname,
        content: menulist,
        iconCls: 'icon ' + n.icon
    });

});

$('.easyui-accordion li a').click(function(){
    var tabTitle = $(this).children('.nav').text();
    var url = $(this).attr("rel");
    var menuid = $(this).attr("ref");
    var icon = getIcon(menuid,icon);
    addTab(tabTitle,url,icon);
    $('.easyui-accordion li div').removeClass("selected");
    $(this).parent().addClass("selected");
}).hover(function(){
    $(this).parent().addClass("hover");
},function(){
    $(this).parent().removeClass("hover");
});

//选中第一个
var panels = $('#nav').accordion('panels');
var t = panels[0].panel('options').title;
$('#nav').accordion('select', t);
}

//构建菜单树(递归方式) BEGIN
function createMenuTree(node){
var menuTree= {};
if (node.level=='1'){
    menuTree.menus = [];
    for (var i in node.children){
        menuTree.menus.push( createMenuTree(node.children[i]));
    }
} else if (node.level=='2') {
    menuTree.menuid = node.object.function_id;
    menuTree.menuname = node.object.function_name;
    menuTree.icon = 'icon-sys';
    menuTree.menus = [];
    for (var i in node.children){
        menuTree.menus.push( createMenuTree(node.children[i]));
    }
} else if (node.level=='3') {
    menuTree.menuid = node.object.function_id;
    menuTree.menuname = node.object.function_name;
    menuTree.icon = 'icon-nav';
    menuTree.menus = [];
    for (var i in node.children){
        menuTree.menus.push( createMenuTree(node.children[i]));
    }
} else if (node.level=='4') {
    menuTree.menuid = node.object.function_id;
    menuTree.menuname = node.object.function_name;
    menuTree.icon = 'icon-nav';
    menuTree.url = contextPath()+"/"+node.object.function_url;
}
return menuTree;
}
//构建菜单树(递归方式)  END

//获取左侧导航的图标
function getIcon(menuid){
var icon = 'icon ';
$.each(_menus.menus, function(i, n) {
     $.each(n.menus, function(j, o) {
         $.each(o.menus, function(k, l) {
            if (l.menuid==menuid) icon += o.icon;
        })
     })
});
return icon;
}

function addTab(subtitle,url,icon){
if(!$('#tabs').tabs('exists',subtitle)){
    $('#tabs').tabs('add',{
        title:subtitle,
        content:createFrame(url),
        //icon:icon,  //设置页面的图标
        closable:true
    });
}else{
    $('#tabs').tabs('select',subtitle);
    $('#mm-tabupdate').click();
}
tabClose();
}

function createFrame(url)
{
var s = '<iframe scrolling="auto" frameborder="0"  src="'+url+'" style="width:100%;height:100%;"></iframe>';
return s;
}

function tabClose()
{
/*双击关闭TAB选项卡*/
$(".tabs-inner").dblclick(function(){
    var subtitle = $(this).children(".tabs-closable").text();
    $('#tabs').tabs('close',subtitle);
});
/*为选项卡绑定右键*/
$(".tabs-inner").bind('contextmenu',function(e){
    $('#mm').menu('show', {
        left: e.pageX,
        top: e.pageY
    });
    var subtitle =$(this).children(".tabs-closable").text();
    $('#mm').data("currtab",subtitle);
    $('#tabs').tabs('select',subtitle);
    return false;
});
}
//绑定右键菜单事件
function tabCloseEven()
{
//刷新
$('#mm-tabupdate').click(function(){
    var currTab = $('#tabs').tabs('getSelected');
    var url = $(currTab.panel('options').content).attr('src');
    $('#tabs').tabs('update',{
        tab:currTab,
        options:{
            content:createFrame(url)
        }
    })
});
//关闭当前
$('#mm-tabclose').click(function(){
    var currtab_title = $('#mm').data("currtab");
    $('#tabs').tabs('close',currtab_title);
});
//全部关闭
$('#mm-tabcloseall').click(function(){
    $('.tabs-inner span').each(function(i,n){
        var t = $(n).text();
        $('#tabs').tabs('close',t);
    });
});
//关闭除当前之外的TAB
$('#mm-tabcloseother').click(function(){
    $('#mm-tabcloseright').click();
    $('#mm-tabcloseleft').click();
});
//关闭当前右侧的TAB
$('#mm-tabcloseright').click(function(){
    var nextall = $('.tabs-selected').nextAll();
    if(nextall.length==0){
        //msgShow('系统提示','后边没有啦~~','error');
        alert('后边没有啦~~');
        return false;
    }
    nextall.each(function(i,n){
        var t=$('a:eq(0) span',$(n)).text();
        $('#tabs').tabs('close',t);
    });
    return false;
});
//关闭当前左侧的TAB
$('#mm-tabcloseleft').click(function(){
    var prevall = $('.tabs-selected').prevAll();
    if(prevall.length==0){
        alert('到头了，前边没有啦~~');
        return false;
    }
    prevall.each(function(i,n){
        var t=$('a:eq(0) span',$(n)).text();
        $('#tabs').tabs('close',t);
    });
    return false;
});

//退出
$("#mm-exit").click(function(){
    $('#mm').menu('hide');
});
}

//弹出信息窗口 title:标题 msgString:提示信息 msgType:信息类型 [error,info,question,warning]
function msgShow(title, msgString, msgType) {
$.messager.alert(title, msgString, msgType);
}

//设置登录窗口
function openPwd() {
    $('#w').window({
        title: '修改密码',
        width: 300,
        modal: true,
        shadow: true,
        closed: true,
        height: 190,
        resizable:false
    });
}
//关闭登录窗口
function closePwd() {
    $('#w').window('close');
}



//修改密码
function serverLogin() {
    var $oldpass = $('#txtOldPass');
    var $newpass = $('#txtNewPass');
    var $rePass = $('#txtRePass');

    if ($oldpass.val() == '') {
        msgShow('系统提示', '请输入原密码！', 'warning');
        return false;
    }
    if ($newpass.val() == '') {
        msgShow('系统提示', '请输入新密码！', 'warning');
        return false;
    }
    if ($rePass.val() == '') {
        msgShow('系统提示', '请在一次输入新密码！', 'warning');
        return false;
    }

    if ($newpass.val() != $rePass.val()) {
        msgShow('系统提示', '新密码两次输入不一至！请重新输入', 'warning');
        return false;
    }

    $.ajax({
        type:'POST',
        url:contextPath()+'/auth/modifyLoginUserPassword',
        data:{	oldpassword:$oldpass.val(),
                newpassword:$newpass.val()},
        dataType:'json',
        beforeSend: function () {
            $.messager.progress({
                title: '提示',
                msg: '操作进行中，请稍候……',
                text: ''
            });
        },
        complete: function () {
            $.messager.progress('close');
        },
        success: function(result){
            if (result) {
                msgShow('系统提示', '恭喜，密码修改成功！<br>您的新密码为：' + $newpass.val(), 'info');
                $newpass.val('');
                $rePass.val('');
                closePwd();
            } else {
                msgShow('系统提示', '密码修改失败！', 'info');
            }
        }
    });
}

$(function() {

    var res1 = $.ajax({url:contextPath()+"/auth/getLoginUser",async:false});
    var res2 = $.ajax({url:contextPath()+"/auth/getLoginRole",async:false});
    var res3 = eval("(" + res1.responseText + ")");
    var res4 = eval("(" + res2.responseText + ")");
    var loginUserName = res3.login_user.name_cn;
    var loginRoleName = res4.login_role.role_name;
    $("#LoginUserInfo").html(loginUserName + "|" + loginRoleName);

    openPwd();

    $('#editpass').click(function() {
        $('#w').window('open');
    });

    $('#btnEp').click(function() {
        serverLogin();
    })

    $('#btnCancel').click(function(){closePwd();})

    $('#logout').click(function() {
        $.messager.confirm('系统提示', '您确定要退出本次登录吗?', function(r) {
            if (r) {
                location.href = contextPath()+'/authlogin/logout';
            }
        });
    })

    //初始化左侧菜单
    InitLeftMenu();
    tabClose();
    tabCloseEven();

});